/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.excel;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.mapper.query.ConditionEnum;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.PlatformService;
import com.je.common.base.service.rpc.FunInfoRpcService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Excel导出
 */
public abstract class AbstractExcelRpcExportService implements ExcelRpcExportService {

    @Autowired
    protected SystemVariableRpcService systemVariableRpcService;
    @Autowired
    protected SystemSettingRpcService systemSettingRpcService;
    @Autowired
    protected CommonService commonService;
    @Autowired
    protected PlatformService manager;
    @Autowired
    protected MetaService metaService;
    @Autowired
    protected ExcelRpcService excelRpcService;
    @Autowired
    private FunInfoRpcService funInfoRpcService;

    private static final String COLUMNS = "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE," +
            "RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO";


    /**
     * 核心表 - 后续补充
     */
    List<String> CORE_TABLE = Lists.newArrayList("JE_CORE_DICTIONARY");

    /**
     * saas表过滤用
     */
    List<String> SAAS_TABLE = Lists.newArrayList("JE_CORE_ENDUSER", "JE_CORE_DEPARTMENT");

    /**
     * 不是源码用户
     */
    private static final String IS_CORE = "1";
    /**
     * 存储过程
     */
    private static final String IDITPROCEDURE = "iditprocedure";

    public List<DynaBean> getDate(JSONObject params, HttpServletRequest request) {
        //查询数据
        List<DynaBean> datas = expData(params, request);
        return datas;
    }

    public List<DynaBean> expData(JSONObject params, HttpServletRequest request) {
        String jQuery = params.getString("j_query");
        String tableCode = params.getString("tableCode");
        String funcId = params.getString("funcId");
        String funcCode = params.getString("funcCode");
        String whereSql = params.getString("whereSql");
        String orderSql = params.getString("orderSql");
        String queryType = params.getString("queryType");
        String datasourceName = params.getString("datasourceName");
        String procedureName = params.getString("procedureName");
        String dbSql = params.getString("dbSql");
        String queryParamStr = params.getString("queryParamsStr");
        String queryParamValueStr = params.getString("dbQueryObj");

        Query query = Query.build(jQuery);
        //添加核心表数据过滤和租户过滤
        filterCoreTable(tableCode, query);
        filterTenants(tableCode, query);

        BaseMethodArgument baseMethodArgument = new BaseMethodArgument();
        //设置查询参数
        baseMethodArgument.setjQuery(JSON.toJSONString(query));
        //不分页
        baseMethodArgument.setLimit(-1);
        //添加参数
        baseMethodArgument.setFuncId(funcId);
        baseMethodArgument.setFuncCode(funcCode);
        baseMethodArgument.setTableCode(tableCode);
        baseMethodArgument.setWhereSql(whereSql);
        baseMethodArgument.setOrderSql(orderSql);
        baseMethodArgument.setQueryType(queryType);
        baseMethodArgument.setDatasourceName(datasourceName);
        baseMethodArgument.setProcedureName(procedureName);
        baseMethodArgument.setQueryParamsStr(queryParamStr);
        baseMethodArgument.setDbQueryObj(queryParamValueStr);
        baseMethodArgument.setDbSql(dbSql);
        /**
         * 获取该功能的所有表单字段
         */
        List records = manager.load(baseMethodArgument, request).getRecords();

        //转换DynaBean
        ArrayList<DynaBean> datas = Lists.newArrayList();
        DynaBean bean;
        for (Object record : records) {
            if (!(record instanceof Map)) {
                continue;
            }
            bean = new DynaBean();
            if (StringUtils.isNotBlank(tableCode)) {
                bean.table(tableCode);
            }
            bean.fetchAllValues().putAll((Map) record);
            datas.add(bean);
        }
        return datas;
    }

    /**
     * 判断是否是核心表，核心表加上 SY_JECORE 条件,过滤核心数据
     */
    private void filterCoreTable(String tableCode, Query query) {
        if (StringUtil.isNotEmpty(tableCode) && CORE_TABLE.contains(tableCode.toUpperCase())) {
            Condition condition = query.findCondition("SY_JESYS", "1");
            if (IS_CORE.equals(systemVariableRpcService.requireSystemVariable("SY_JECORE"))) {
                if (condition != null) {
                    condition.setCode("");
                    condition.setType("or".equalsIgnoreCase(condition.getCn()) ? ConditionEnum.OR.getType() : ConditionEnum.AND.getType());
                    Condition sysJesys = new Condition("SY_JESYS", ConditionEnum.EQ.getType(), "1");
                    Condition sysJecore = new Condition("SY_JECORE", ConditionEnum.NE.getType(), "1", ConditionEnum.OR.getType());
                    condition.setValue(Lists.newArrayList(sysJesys, sysJecore));
                } else {
                    query.addCustom("SY_JECORE", ConditionEnum.NE, "1");
                }
            } else if (condition != null) {
                query.getCustom().remove(condition);
            }
        }
    }

    /**
     * 过滤租户
     */
    private void filterTenants(String tableCode, Query query) {
        //租户过滤条件
        if (StringUtil.isNotEmpty(tableCode) && systemSettingRpcService.isSaas() && SAAS_TABLE.contains(tableCode.toUpperCase())) {
            if (query.findCondition("ZHID") == null) {
                query.addCustom("ZHID", ConditionEnum.EQ, SecurityUserHolder.getCurrentAccountTenantId());
            }
        }
    }

    /**
     * build格式化数据，获取最终展示在Excel上的数据
     *
     * @param datas       数据
     * @param ddInfos     字典配置
     * @param formColumns 表单配置
     * @return
     */
    /*public List<List<Object>> buildExportData(String funcId, List<DynaBean> datas, Map<String, Map<String, String>> ddInfos, List<DynaBean> formColumns) {
        return excelRpcService.buildExportData(funcId,datas,ddInfos,formColumns);
    }*/
    /*public List<List<Object>> buildExportData(String funcId, List<DynaBean> datas, Map<String, Map<String, String>> ddInfos, List<DynaBean> formColumns) {
        List<DynaBean> funcGridFileds = metaService.select("JE_CORE_RESOURCECOLUMN", ConditionsWrapper.builder()
                .eq("RESOURCECOLUMN_FUNCINFO_ID", funcId).in("RESOURCECOLUMN_XTYPE", "rownumberer", "uxcolumn")
                .eq("RESOURCECOLUMN_HIDDEN", "0").orderByAsc("SY_ORDERINDEX"), COLUMNS);
        List<List<Object>> list = new ArrayList<>();
        int i = 1;
        for (DynaBean dynaBean : datas) {
            List<Object> dataMap = new ArrayList<>();
            HashMap<String, Object> map = dynaBean.getValues();
            for (DynaBean gridFiled : funcGridFileds) {
                String filedCode = gridFiled.getStr("RESOURCECOLUMN_CODE");
                String type = gridFiled.getStr("RESOURCECOLUMN_XTYPE");
                if (type.equals("rownumberer")) {
                    dataMap.add(i);
                    i++;
                    continue;
                }
                DynaBean formColumn = null;
                for (DynaBean fc : formColumns) {
                    if (fc.getStr("RESOURCECOLUMN_CODE").equals(filedCode)) {
                        formColumn = fc;
                    }
                }
                if (formColumn == null) {
                    throw new PlatformException(String.format("获取%s导出字段配置信息出错！", filedCode), PlatformExceptionEnum.UNKOWN_ERROR);
                }
                Object value = buildValue(map.get(filedCode), formColumn, ddInfos);
                dataMap.add(value);
            }
            list.add(dataMap);
        }
        return list;
    }


    private Object buildValue(Object value, DynaBean formColumn, Map<String, Map<String, String>> ddInfos) {
        if (Objects.isNull(value)) {
            return "";
        }
        String stringValue = String.valueOf(value);
        if (Strings.isNullOrEmpty(stringValue)) {
            return "";
        }
        String type = formColumn.getStr("RESOURCEFIELD_XTYPE");
        return ExcelExportConverterFactory.getConverter(type).converter(stringValue, formColumn, ddInfos);
    }*/


}
